package org.idea.spring.bean.beaninit;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;

import java.util.Arrays;

/**
 * @Author idea
 * @Date created in 8:16 上午 2020/7/10
 */
public class SpringTestInitBeanDemo {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        //将指定的bean注册到spring容器里，并且指定的bean如果内部也有被声明为bean的部分也会被注册
        System.out.println("[before]:" + Arrays.toString(applicationContext.getBeanDefinitionNames()));
        int count1 = applicationContext.getBeanDefinitionCount();
        applicationContext.register(SpringTestInitBeanDemo.class);
        int count2 = applicationContext.getBeanDefinitionCount();
        System.out.println("[after]:" + Arrays.toString(applicationContext.getBeanDefinitionNames()));
        System.out.println("before register :" + count1 + " after register:" + count2);
        applicationContext.refresh();

        //首先触发@PostConstruct 然后是 afterPropertiesSet 最后是 @Bean(initMethod = "init2")
        System.out.println("spring容器已经开启====");
        PeopleFactory peopleFactory = applicationContext.getBean(PeopleFactory.class);
        applicationContext.close();
    }

    /**
     * 由于applicationContext.register注册了对应的bean，所以这里会生效
     *
     * @return
     */
    @Bean(initMethod = "init2")
    @Lazy
    public PeopleFactory createPeople() {
        return new DefaultPeopleFactory();
    }
}
